﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using System.Drawing.Drawing2D;
using Microsoft.Win32;
using System.Collections;
using System.Runtime.InteropServices;
using System.Xml;
using System.Drawing.Imaging;
namespace 会员卡管理系统
{
    public partial class SysSet : UserControl
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);

        int screenWidth = Screen.PrimaryScreen.Bounds.Width;
        int screenHeight = Screen.PrimaryScreen.Bounds.Height;
        FileInfo[] picFiles;
        string password=null;
        int intok = 0;
        bool ok1=false;
        bool ok2 = false;
        bool ok3 = false;

        public SysSet()
        {
            InitializeComponent();
        }
        Vipclass.tbVipHouseMenthod setmenthod = new Vipclass.tbVipHouseMenthod();
        private void SysSet_Load(object sender, EventArgs e)
        {
            if (File.Exists(Application.StartupPath + @"\kaijiziqi"))
            {
                checkBox2.Checked = true;
            }
        }

        private void btnOpencalc_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(@"C:\WINDOWS\system32\calc.exe");
        }

        private void button4_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("notepad.exe");
            
        }

        private void groupBox4_Enter(object sender, EventArgs e)
        {
            List<DictionaryEntry> list = new List<DictionaryEntry>(){
                new DictionaryEntry(1, "居中显示"),
                new DictionaryEntry(2, "平铺显示"),
                new DictionaryEntry(3, "拉伸显示")
            };
            cbWallpaperStyle.DisplayMember = "Value";
            cbWallpaperStyle.ValueMember = "Key";
            cbWallpaperStyle.DataSource = list;

            txtPicDir.Text = XmlNodeInnerText("");
            timer1.Tick += new EventHandler(timer_Tick);
            labtxt.Text = string.Format("设置桌面壁纸(当前电脑分辨率{0}×{1})", screenWidth, screenHeight);
        }
        /// <summary>
        /// 浏览单个图图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "Images (*.BMP;*.JPG)|*.BMP;*.JPG;";
                openFileDialog.AddExtension = true;
                openFileDialog.RestoreDirectory = true;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    Bitmap img = (Bitmap)Bitmap.FromFile(openFileDialog.FileName);
                    pictureBox1.Image = img;
                    string msg = (img.Width != screenWidth || img.Height != screenHeight) ? "，建议选择和桌面分辨率一致图片" : "";
                    labtxt.Text = string.Format("当前图片分辨率{0}×{1}{2}", img.Width, img.Height, msg);
                }
            }
        }
        /// <summary>
        /// 手动设置壁纸
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSet_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image == null)
            {
                MessageBox.Show("请先选择一张图片。");
                return;
            }
            Image img = pictureBox1.Image;
            SetWallpaper(img);
        }
        private void SetWallpaper(Image img)
        {
            Bitmap bmp = Calendar.GetCalendarPic(img);
            string filename = Application.StartupPath + "/wallpaper.bmp";
            bmp.Save(filename, ImageFormat.Bmp);

            string tileWallpaper = "0";
            string wallpaperStyle = "0";
            string selVal = cbWallpaperStyle.SelectedValue.ToString();
            if (selVal == "1")
                tileWallpaper = "1";
            else if (selVal == "2")
                wallpaperStyle = "2";

            //写到注册表，避免系统重启后失效
            RegistryKey regKey = Registry.CurrentUser;
            regKey = regKey.CreateSubKey("Control Panel\\Desktop");
            //显示方式，居中：0 0， 平铺： 1 0， 拉伸： 0 2
            regKey.SetValue("TileWallpaper", tileWallpaper);
            regKey.SetValue("WallpaperStyle", wallpaperStyle);
            regKey.SetValue("Wallpaper", filename);
            regKey.Close();
            SystemParametersInfo(20, 1, filename, 1);
        }
        /// <summary>
        /// 浏览文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBrowseDir_Click(object sender, EventArgs e)
        {
            string defaultfilePath = XmlNodeInnerText("");
            using (FolderBrowserDialog dialog = new FolderBrowserDialog())
            {
                if (defaultfilePath != "")
                    dialog.SelectedPath = defaultfilePath;

                if (dialog.ShowDialog() == DialogResult.OK)
                    XmlNodeInnerText(dialog.SelectedPath);

                txtPicDir.Text = dialog.SelectedPath;
            }
        }
        /// <summary>
        /// 获取或设置配置文件中的选择目录
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string XmlNodeInnerText(string text)
        {
            string filename = Application.StartupPath + "/config.xml";
            XmlDocument doc = new XmlDocument();
            if (!File.Exists(filename))
            {
                XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(dec);
                XmlElement elem = doc.CreateElement("WallpaperPath");
                elem.InnerText = text;
                doc.AppendChild(elem);
                doc.Save(filename);
            }
            else
            {
                doc.Load(filename);
                XmlNode node = doc.SelectSingleNode("//WallpaperPath");
                if (node != null)
                {
                    if (string.IsNullOrEmpty(text))
                        return node.InnerText;
                    else
                    {
                        node.InnerText = text;
                        doc.Save(filename);
                    }
                }
            }
            return text;
        }
        /// <summary>
        /// 定时自动设置壁纸
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAutoSet_Click(object sender, EventArgs e)
        {
            string path = txtPicDir.Text;
            if (!Directory.Exists(path))
            {
                MessageBox.Show("选择的文件夹不存在");
                return;
            }
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            picFiles = dirInfo.GetFiles("*.jpg");
            if (picFiles.Length == 0)
            {
                MessageBox.Show("选择的文件夹里面没有图片");
                return;
            }
            if (btnAutoSet.Text == "开始")
            {
                timer1.Start();
                btnAutoSet.Text = "停止";
                labtxt.Text = string.Format("定时自动换壁纸中...");
            }
            else
            {
                timer1.Stop();
                btnAutoSet.Text = "开始";
                labtxt.Text = "";
            }
        }
        /// <summary>
        /// 定时随机设置壁纸
        /// </summary>
        private void timer_Tick(object sender, EventArgs e)
        {
            timer1.Interval = 1000 * 60 * (int)numericUpDown1.Value;
            FileInfo[] files = picFiles;
            if (files.Length > 0)
            {
                Random random = new Random();
                int r = random.Next(1, files.Length);

                Bitmap img = (Bitmap)Bitmap.FromFile(files[r].FullName);
                pictureBox1.Image = img;

                SetWallpaper(img);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否保存修改？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                //此处运用一个窗体修改另外一个窗体事件
                Mainfrm f1 = (Mainfrm)Mainfrm.ActiveForm;
                if (checkBox1.Checked == false)
                {
                    f1.notifyIcon1.Visible = false;
                }
                else
                {
                    f1.notifyIcon1.Visible = true;
                }
                if(checkBox2.Checked)
                {
                    //Registry.LocalMachine.CreateSubKey(@"SOFTWARE\MICROSOFT\WINDOWS\CURRENTVERSION\RUN").SetValue("MyVipSys", Application.StartupPath + "\\会员管理系统.exe", RegistryValueKind.String);
                    //RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);//打开注册表子项  
                    //key.SetValue("会员卡管理系统", Application.StartupPath);
                    //setmenthod.SetAutoRun(Application.ExecutablePath, true);
                    try
                    {
                        RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\microsoft\windows\currentversion\run", true);
                        if (key != null) key.SetValue("会员卡管理系统.exe", Application.ExecutablePath);
                        MessageBox.Show("开机自启成功，请重新启动电脑查看效果！", "提示");
                        key.Close();
                        FileStream fs = new FileStream("kaijiziqi", FileMode.OpenOrCreate);
                        fs.Close();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                else
                {
                    //setmenthod.SetAutoRun(Application.ExecutablePath, false);
                    try
                    {
                        RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\microsoft\windows\currentversion\run", true);
                        object obj = key.GetValue("会员卡管理系统.exe");
                        //if (key.GetValue("WindowsFormsApplication1.exe").ToString().Length>0)
                        if (obj != null)
                        {
                            key.DeleteValue("会员卡管理系统.exe");
                            MessageBox.Show("取消开机启动成功！", "提示");
                        }
                        else
                        {
                            MessageBox.Show("点击次数过多！");
                        }
                        key.Close();
                        string pSavedPath1 = "kaijiziqi";
                        if (File.Exists(pSavedPath1))
                        {
                            FileInfo fi = new FileInfo(pSavedPath1);
                            if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                                fi.Attributes = FileAttributes.Normal;
                            File.Delete(pSavedPath1);
                        }

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
                MessageBox.Show("修改成功！", "提示");
            }
            else
            {

            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            
            if(intok==0)
            {
                if (File.Exists(Application.StartupPath + @"\AdminPassWord.txt"))
                {
                    FileInfo fi = new FileInfo("AdminPassWord.txt");
                    StreamReader sr = fi.OpenText();
                    password = sr.ReadLine();
                    sr.Close();
                    intok=1;
                }  
            }
            if (textBox1.Text == password)
            {
                pBxpw1.Image = Properties.Resources.gqq;
                intok = 0;
                ok1 = true;
            }
            else
            {
                pBxpw1.Image = Properties.Resources.gqp;
                ok1 = false;
            }
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            if(textBox2.Text.Length>=5)
            {
                pBxpw2.Image = Properties.Resources.gqq;
                ok2 = true;
            }
            else
            {
                pBxpw2.Image = Properties.Resources.gqp;
                ok2 = false;
            }
            textBox3_TextChanged(null, null);
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            if(textBox3.Text.Length>=5)
            {
                if(textBox3.Text==textBox2.Text)
                {
                    pBxpw3.Image = Properties.Resources.gqq;
                    ok3 = true;
                }
                else
                {
                    pBxpw3.Image = Properties.Resources.gqp;
                    ok3 = false;
                }
            }
            else
            {
                pBxpw3.Image = Properties.Resources.gqp;
                ok3 = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(ok1==true&&ok2==true&&ok3==true)
            {
                if(MessageBox.Show("是否修改密码？","提示",MessageBoxButtons.YesNo,MessageBoxIcon.Information)==DialogResult.Yes)
                {
                    if(password!=textBox3.Text)
                    {
                        try
                        {
                            using (StreamWriter writer = new StreamWriter(Application.StartupPath + "\\AdminPassWord.txt"))
                            {
                                writer.WriteLine(textBox3.Text);
                            }
                            MessageBox.Show("密码修改成功，请重新登陆！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            Application.Restart();
                        }
                        catch (Exception err)
                        {
                            MessageBox.Show(err.Message.ToString());
                            button2_Click(null, null);
                        }
                    }
                    else
                    {
                        MessageBox.Show("密码与原密码重复，请重新修改！", "提示");
                        textBox1.Text = "";
                        textBox2.Text = "";
                        textBox3.Text = "";
                    }
                }
            }
            else
            {
                if (textBox1.Text == "" || textBox3.Text == "" || textBox2.Text == "")
                {
                    MessageBox.Show("输入为空！", "提示");
                }
                else
                {
                    MessageBox.Show("输入有误，请重新输入！", "提示");
                    textBox1.Text = "";
                    textBox2.Text = "";
                    textBox3.Text = "";
                }
            }
        }
    }
}
